import 'package:dailoz/enum/modify_task_enum.dart';
import 'package:dailoz/generated/l10n.dart';
import 'package:dailoz/service/tag_service/tag_service.dart';
import 'package:dailoz/size_config.dart';
import 'package:dailoz/utils/showAlertDialog.dart';
import 'package:dailoz/utils/toast.dart';
import 'package:dailoz/view_model/modify_page_view_model.dart';
import 'package:dailoz/widgets/button_widget.dart';
import 'package:dailoz/widgets/date_picker_item.dart';
import 'package:dailoz/widgets/dialog.dart';
import 'package:dailoz/widgets/progress_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ModifyPage extends StatefulWidget {
  const ModifyPage({Key? key, this.taskId}) : super(key: key);

  static String id = "modifyPageId";

  final String? taskId;

  @override
  State<ModifyPage> createState() => _ModifyPageState();
}

class _ModifyPageState extends State<ModifyPage> {
  TextEditingController? titleController;
  TextEditingController? desController;
  TextEditingController? tagNameController;

  ModifyPageViewModel? _modifyPageViewModel;

  init() async {
    _modifyPageViewModel = ModifyPageViewModel();
    await _modifyPageViewModel!.fetchTask(widget.taskId);
    await _modifyPageViewModel!.fetchTagList();
  }

  @override
  void initState() {
    super.initState();
    titleController = TextEditingController();
    desController = TextEditingController();
    tagNameController = TextEditingController();
    init();
  }

  @override
  void dispose() {
    titleController!.dispose();
    desController!.dispose();
    tagNameController!.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => _modifyPageViewModel,
      child: Consumer<ModifyPageViewModel>(
        builder: (context, provider, _) {
          titleController!.text = provider.taskContent!;
          desController!.text = provider.description!;
          return Scaffold(
            body: ProgressWidget(
              loading: provider.isLoading,
              msg: S.of(context).isLoading,
              child: SingleChildScrollView(
                child: Stack(
                  children: [
                    Positioned(
                      top: SizeConfig.getProportionateScreenHeight(56.0),
                      left: SizeConfig.getProportionateScreenWidth(30.0),
                      child: Container(
                        height: SizeConfig.getProportionateScreenHeight(42.0),
                        width: SizeConfig.getProportionateScreenWidth(42.0),
                        decoration: BoxDecoration(
                          // color: Theme.of(context).buttonTheme.get,
                          borderRadius: const BorderRadius.all(
                            Radius.circular(14.0),
                          ),
                        ),
                        child: IconButton(
                          onPressed: () {
                            Navigator.pop(context);
                          },
                          icon: Icon(
                            Icons.arrow_back_ios_outlined,
                            color: Theme.of(context).textTheme.bodyText2?.color,
                            size: SizeConfig.getProportionateFontSize(14.0),
                          ),
                        ),
                      ),
                    ),
                    Center(
                      child: SizedBox(
                        width: SizeConfig.getProportionateScreenWidth(327.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Padding(
                              padding: const EdgeInsets.only(top: 68.0),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Text(
                                    S.of(context).modify,
                                    style: Theme.of(context).textTheme.bodyText2?.copyWith(
                                          fontSize: SizeConfig.getProportionateFontSize(18.0),
                                          fontWeight: FontWeight.w500,
                                        ),
                                  ),
                                ],
                              ),
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Padding(
                                  padding: const EdgeInsets.only(top: 25.0),
                                  child: Text(
                                    S.of(context).title,
                                    style: TextStyle(
                                      fontSize: SizeConfig.getProportionateFontSize(14.0),
                                      color: const Color(0xff8a8bb3),
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  height: SizeConfig.getProportionateScreenHeight(35.0),
                                  child: TextField(
                                    controller: titleController,
                                  ),
                                ),
                              ],
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Padding(
                                  padding: const EdgeInsets.only(top: 25.0),
                                  child: Text(
                                    S.of(context).date,
                                    style: TextStyle(
                                      fontSize: SizeConfig.getProportionateFontSize(14.0),
                                      color: const Color(0xff8a8bb3),
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  height: SizeConfig.getProportionateScreenHeight(35.0),
                                  child: DatePickerItem(
                                    children: <Widget>[
                                      Text(
                                        '${provider.date?.year}-${provider.date?.month.toString().padLeft(2, "0")}-${provider.date?.day.toString().padLeft(2, "0")}',
                                        style: Theme.of(context).textTheme.bodyText2?.copyWith(
                                              fontSize: SizeConfig.getProportionateFontSize(16.0),
                                            ),
                                      ),
                                      IconButton(
                                        onPressed: () => ShowDialog.showDialog(
                                          context,
                                          CupertinoDatePicker(
                                            initialDateTime: provider.date,
                                            mode: CupertinoDatePickerMode.date,
                                            use24hFormat: true,
                                            // This is called when the user changes the time.
                                            onDateTimeChanged: (DateTime newTime) {
                                              setState(() => provider.changeDate(newTime));
                                            },
                                          ),
                                        ),
                                        // onPressed: null,
                                        icon: Icon(
                                          Icons.calendar_month_outlined,
                                          color: const Color(0xff10275a),
                                          size: SizeConfig.getProportionateFontSize(20.0),
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Padding(
                                  padding: const EdgeInsets.only(top: 25.0),
                                  child: Text(
                                    S.of(context).time,
                                    style: TextStyle(
                                      fontSize: SizeConfig.getProportionateFontSize(14.0),
                                      color: const Color(0xff8a8bb3),
                                    ),
                                  ),
                                ),
                                Row(
                                  children: [
                                    SizedBox(
                                      width: SizeConfig.getProportionateScreenWidth(147.0),
                                      child: DatePickerItem(
                                        rowMainAxisAlignment: MainAxisAlignment.center,
                                        children: <Widget>[
                                          TextButton(
                                            onPressed: () {
                                              ShowDialog.showDialog(
                                                context,
                                                CupertinoDatePicker(
                                                  initialDateTime: provider.startTime,
                                                  mode: CupertinoDatePickerMode.time,
                                                  onDateTimeChanged: (newTime) {
                                                    setState(() {
                                                      provider.changeStartTime(newTime);
                                                    });
                                                  },
                                                ),
                                              );
                                            },
                                            child: Text(
                                              '${provider.startTime?.hour.toString().padLeft(2, "0")}:${provider.startTime?.minute.toString().padLeft(2, "0")}',
                                              style: Theme.of(context).textTheme.bodyText2?.copyWith(
                                                    fontSize: SizeConfig.getProportionateFontSize(18.0),
                                                  ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                    SizedBox(
                                      width: SizeConfig.getProportionateScreenWidth(20.0),
                                    ),
                                    SizedBox(
                                      width: SizeConfig.getProportionateScreenWidth(147.0),
                                      child: DatePickerItem(
                                        rowMainAxisAlignment: MainAxisAlignment.center,
                                        children: <Widget>[
                                          TextButton(
                                            onPressed: () {
                                              ShowDialog.showDialog(
                                                context,
                                                CupertinoDatePicker(
                                                  initialDateTime: provider.endTime,
                                                  mode: CupertinoDatePickerMode.time,
                                                  onDateTimeChanged: (newTime) {
                                                    setState(() {
                                                      provider.changeEndTime(newTime);
                                                    });
                                                  },
                                                ),
                                              );
                                            },
                                            child: Text(
                                              '${provider.endTime?.hour.toString().padLeft(2, "0")}:${provider.endTime?.minute.toString().padLeft(2, "0")}',
                                              style: Theme.of(context).textTheme.bodyText2?.copyWith(
                                                    fontSize: SizeConfig.getProportionateFontSize(18.0),
                                                  ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Padding(
                                  padding: const EdgeInsets.only(top: 25.0),
                                  child: Text(
                                    S.of(context).description,
                                    style: TextStyle(
                                      fontSize: SizeConfig.getProportionateFontSize(14.0),
                                      color: const Color(0xff8a8bb3),
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  height: SizeConfig.getProportionateScreenHeight(35.0),
                                  child: TextField(
                                    controller: desController,
                                  ),
                                ),
                              ],
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Padding(
                                  padding: const EdgeInsets.only(top: 25.0),
                                  child: Text(
                                    S.of(context).type,
                                    style: TextStyle(
                                      fontSize: SizeConfig.getProportionateFontSize(14.0),
                                      color: const Color(0xff8a8bb3),
                                    ),
                                  ),
                                ),
                                Wrap(
                                  spacing: SizeConfig.getProportionateScreenWidth(30.0),
                                  children: [
                                    Row(
                                      mainAxisSize: MainAxisSize.min,
                                      children: [
                                        Radio(
                                          value: "normal",
                                          groupValue: provider.groupValue,
                                          onChanged: (value) {
                                            provider.changeGroupValue(value);
                                          },
                                        ),
                                        Text(
                                          "Normal",
                                          style: Theme.of(context).textTheme.bodyText2?.copyWith(
                                                fontSize: SizeConfig.getProportionateFontSize(16.0),
                                              ),
                                        ),
                                      ],
                                    ),
                                    Row(
                                      mainAxisSize: MainAxisSize.min,
                                      children: [
                                        Radio(
                                          value: "urgent",
                                          groupValue: provider.groupValue,
                                          onChanged: (value) {
                                            provider.changeGroupValue(value);
                                          },
                                        ),
                                        Text(
                                          "Urgent",
                                          style: Theme.of(context).textTheme.bodyText2?.copyWith(
                                                fontSize: SizeConfig.getProportionateFontSize(16.0),
                                              ),
                                        )
                                      ],
                                    ),
                                  ],
                                )
                              ],
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Padding(
                                  padding: const EdgeInsets.only(top: 25.0),
                                  child: Text(
                                    S.of(context).tags,
                                    style: TextStyle(
                                      fontSize: SizeConfig.getProportionateFontSize(14.0),
                                      color: const Color(0xff8a8bb3),
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  height: SizeConfig.getProportionateScreenHeight(22.0),
                                ),
                                Wrap(
                                  spacing: SizeConfig.getProportionateScreenWidth(2.0),
                                  runSpacing: SizeConfig.getProportionateScreenHeight(22.0),
                                  children: provider.generateTag(),
                                ),
                              ],
                            ),
                            Column(
                              children: <Widget>[
                                Center(
                                  child: TextButton(
                                    onPressed: () {
                                      showDialog(
                                        context: context,
                                        builder: (BuildContext context) {
                                          return HtmlDialog(
                                            title: "New Tag",
                                            content: TextField(
                                              decoration: const InputDecoration(
                                                border: InputBorder.none,
                                                fillColor: Color(0xfff6f6f6),
                                                filled: true, // filled为true后，fillColor才生效
                                              ),
                                              controller: tagNameController!,
                                            ),
                                            confirmContent: "确定",
                                            cancelContent: S.of(context).Cancel,
                                            confirmCallback: () {
                                              TagService.createTag(context, provider, tagNameController);
                                              // createTag(provider);
                                            },
                                            dismissCallback: () {
                                              Navigator.pop(context);
                                            },
                                          );
                                        },
                                      );
                                    },
                                    child: Text(
                                      "+ ${S.of(context).addNewTag}",
                                      style: Theme.of(context).textTheme.bodyText2?.copyWith(
                                            fontSize: SizeConfig.getProportionateFontSize(
                                              14.0,
                                            ),
                                          ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            Padding(
                              padding: EdgeInsets.only(
                                top: SizeConfig.getProportionateScreenHeight(25.0),
                                bottom: SizeConfig.getProportionateScreenHeight(40.0),
                              ),
                              child: ButtonWidget(
                                width: SizeConfig.getProportionateScreenHeight(327.0),
                                height: SizeConfig.getProportionateScreenHeight(56.0),
                                buttonText: S.of(context).modify,
                                onPressed: () async {
                                  Map<String, dynamic> taskInfo = {};
                                  taskInfo['taskContent'] = titleController!.text;
                                  taskInfo['description'] = desController!.text;
                                  taskInfo['id'] = widget.taskId;
                                  ModifyTaskEnum taskEnum = await provider.modifyTask(taskInfo);
                                  switch (taskEnum) {
                                    case ModifyTaskEnum.taskContentNull:
                                      showToast("任务内容不能为空");
                                      break;
                                    case ModifyTaskEnum.tagNull:
                                      showToast("请指定至少一个标签");
                                      break;
                                    case ModifyTaskEnum.modified:
                                      if (!mounted) return;
                                      Navigator.pop(context);
                                      break;
                                    default:
                                      break;
                                  }
                                },
                                buttonColor: const Color(0xff5b67ca),
                                buttonTextColor: Colors.white,
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        },
        // child: ,
      ),
    );
  }
}
